#!/usr/bin/env python
#coding=utf-8

import os

class BaseProject():
    """BaseProject
    Provide a base class to implement some basic function of a builder.
    Author:Xiognfei GUO
    """
    
    def __init__(self):
        self.source_files = []
        self.project_file_cont = ""
        #self.default_target = None
        
        self.project_dict = {}
        
    def read_project_file(self, file_path):
        my_locals = {}
        try:
            execfile(file_path, globals(), my_locals)
        except  Exception, e:            
            self.report_error("Parse project file error!\nERROR:%s" % e)
        else:
            try:
                self.project_dict = my_locals
            except  Exception, e:
                self.report_error("Parse project file error!\nERROR:%s" % e)
            else:
                return True

        return False
    
    def write_project_file(self, file_path):
        try:
            f = open(file_path, "w")
            pass
        except  Exception, e:
            self.report_error("Can't Write Project File!\nERROR:%s" % e)
        else:
            for k, v in self.project_dict.items():
                f.write("%s = %s\n\n" % (k, str([v])[1:-1]))
            f.close()

    def copy_source_file(self):
        pass
    
    def add_target(self):
        pass
    
    def delete_target(self):
        pass
    
    def set_target(self):
        pass
    
    def set_acvite_target(self):
        pass
    
    def build_target(self, args = []):
        cmd = "scons"
        pipe = os.popen(" ".join([cmd] + args))
        result = pipe.read()
        pipe.close()
        return result
    
    def clean_target(self, args = []):
        cmd = "scons -c"
        args = []
        pipe = os.popen(" ".join([cmd] + args))
        result = pipe.read()
        pipe.close()
        return result
    
    def run(self):
        pass
    
    def debug(self):
        pass
    
    def report_error(self, msg):
        print "ERROR:",msg
    
    
class SimpleCProject(BaseProject):
    def __init__(self):
        BaseProject.__init__(self)
        
    def append_source_file(self, source_file):
        if type(source_file) == type(''):
            if not (source_file in self.project_dict['SOURCE']):
                self.project_dict['SOURCE'].append(source_file)
        elif type(source_file) == type([]):
            for sf in source_file:
                if not (sf in self.project_dict['SOURCE']):
                    self.project_dict['SOURCE'].append(sf)   
                    
    def remove_source_file(self, source_file = '*'):
        if source_file == '*':
            self.project_dict['SOURCE'] = []
        elif type(source_file) == type(''):
            if source_file in self.project_dict['SOURCE']:
                self.project_dict['SOURCE'].remove(source_file)
        elif type(source_file) == type([]):
            for sf in source_file:
                if sf in self.project_dict['SOURCE']:
                    self.project_dict['SOURCE'].remove(sf)
                    
    def set_app_name(self, name):
        self.project_dict['APP_NAME'] = name
        
    def get_project_file_tree(self):
        return {'Source':self.project_dict['SOURCE']}
    
    def run(self, args = []):
        #TODO: detect whether app file exsit.
        cmd = self.project_dict['APP_NAME']

        #TODO: This is not currect for everything
        pipe = os.popen('./' + " ".join([cmd] + args))
        result = pipe.read()
        pipe.close()
        return result 
                
    
if __name__ == "__main__":
    scp = SimpleCProject()
    scp.read_project_file("prj.cfg")
    scp.append_source_file('main.c')
    scp.remove_source_file('main.3c')
    scp.set_app_name('hello')
    scp.write_project_file("prj.cfg")
    
    print scp.clean_target()
    print scp.build_target()
    print scp.get_project_file_tree()
    print scp.run()
